from PyQt5.QtNetwork import QNetworkAccessManager
from PyQt5.QtNetwork import QNetworkRequest
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, QWebEngineProfile
from network.networkutils import *
from network.networkfilter import *
from network.globalfilter import FILTERS

class FilteredPage(QWebEnginePage):
    def acceptNavigationRequest(self, url, _type, isMainFrame):
        try:
            url1 = url.toEncoded().data().decode('utf-8')
            domain = getDomain(url1)
            for filter in FILTERS:
                if not filter.allowRequest(makeNetworkObject(url1, domain, None)):
                    print("YAWK: Network: Request blocked by the filter '" + filter.filterName() + "'.\n\tURL: " + url)
                    return QWebEnginePage.acceptNavigationRequest(self, QUrl(""), _type, isMainFrame)
            return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)
        except Exception as e:
            print(e)
            return QWebEnginePage.acceptNavigationRequest(self, url, _type, isMainFrame)

class FilteredInterceptor(QWebEngineUrlRequestInterceptor):
    def interceptRequest(self, info):
        try:
            url = info.requestUrl().toEncoded().data().decode('utf-8')
            domain = getDomain(url)
            stop = False
            for filter in FILTERS:
                if not filter.allowRequest(makeNetworkObject(url, domain, info)):
                    print("YAWK: Network: Request blocked by the filter '" + filter.filterName() + "'.\n\tURL: " + url)
                    info.block(True)
                    stop = True
                    break
            if stop:
                info.block(True)
                pass
            else:
                print(url)
        except Exception as e:
            print(e)
            pass